#!usr/bin/env python
# -*- coding: utf-8 -*-
import json
import requests

from fx.common.base_redis import rdb
from fx.constants.misc import (
    WEIXIN_SHARE_ACCESS_TOKEN,
    WEIXIN_APP_ID, WEIXIN_APP_SECRET
)


class WxHelper(object):
    def __init__(self):
        self.app_id = WEIXIN_APP_ID
        self.app_secret = WEIXIN_APP_SECRET

    def get_url_data_to_json(self, url):
        resp = requests.get(url)
        return json.loads(resp.text)


class WxShareHelper(WxHelper):

    def __init__(self):
        super(WxShareHelper, self).__init__()
        self.token_url_format = (
            'https://api.weixin.qq.com/cgi-bin/token?'
            'grant_type=client_credential&appid={app_id}&secret={app_secret}'
        )

    def get_access_token_from_wx(self):
        url = self.token_url_format.format(app_id=self.app_id, app_secret=self.app_secret)
        return self.get_url_data_to_json(url)

    def get_access_token(self):
        access_token = rdb.get(WEIXIN_SHARE_ACCESS_TOKEN)
        if not access_token:
            access_token = self.get_access_token_from_wx().get('access_token')
            rdb.setex(WEIXIN_SHARE_ACCESS_TOKEN, 7100, access_token)
        return access_token

    def get_news(self, page, pagesize=50):
        offset = (page - 1) * pagesize
        access_token = self.get_access_token()
        try:
            topics_url = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={access_token}'.format(access_token=access_token)
            resp = requests.post(topics_url, json.dumps(dict(type='news', offset=offset, count=pagesize)))
            resp.encoding = 'utf-8'
            return json.loads(resp.text)
        except Exception, e:
            print e.message
            return {}